<template>
	<view class="content-box">
		<!-- 头部navbar -->
		<navbar :fixed="true" :bgColor="'#fff'" :title="t('my.smrz')" :leftIcon="true"></navbar>

		<!-- 加载状态 -->
		<view v-if="isLoading" class="loading-container">
			<text>加载中...</text>
		</view>

		<!-- 表单容器 - 保持原有样式 -->
		<view v-else class="form-container" :class="{ 'review-container': authStatus === 1 }">
			<!-- 状态提示 -->
			<view v-if="authStatus !== 0" class="status-tip">
				<view class="auth-status-badge" :class="{ 
					'success': authStatus === 2, 
					'pending': authStatus === 1, 
					'failed': authStatus === 3 
				}">
					{{ authStatus === 1 ? '审核中' : authStatus === 2 ? '已认证' : '认证失败' }}
				</view>
			</view>
			<!-- 证件类型 -->
			<view class="form-item">
				<view class="form-label">{{ t('realName.zjlx') }}</view>
				<view class="form-input-container" @click="authStatus === 0 || authStatus === 3 ? showIdTypeSelector = true : null">
					<view class="form-input" :class="{ 'disabled': authStatus === 1 || authStatus === 2 }">
						<image src="/static/icon/zhenjian.svg" class="input-icon"></image>
						<text>{{ cardTypeList[selectedIdType] }}</text>
					</view>
					<image v-if="authStatus === 0 || authStatus === 3" src="/static/icon/xiala2.svg" class="arrow-icon"></image>
				</view>
			</view>

			<!-- 真实姓名 -->
			<view class="form-item">
				<view class="form-label">{{ t('realName.zsxm') }}</view>
				<view class="form-input-container">
					<view class="form-input" :class="{ 'disabled': authStatus === 1 || authStatus === 2 }">
						<image src="/static/icon/xingming.svg" class="input-icon"></image>
						<input 
							type="text" 
							:placeholder="t('realName.qsrzsxm')" 
							v-model="realName" 
							:disabled="authStatus === 1 || authStatus === 2"
						/>
					</view>
				</view>
			</view>

			<!-- 证件号码 -->
			<view class="form-item">
				<view class="form-label">{{ t('realName.zjhm') }}</view>
				<view class="form-input-container">
					<view class="form-input" :class="{ 'disabled': authStatus === 1 || authStatus === 2 }">
						<image src="/static/icon/haoma.svg" class="input-icon"></image>
						<!-- 已认证状态显示脱敏后的身份证号码 -->
						<view v-if="authStatus === 2" class="masked-id-number">
							{{ maskIdNumber(idNumber) }}
						</view>
						<!-- 其他状态显示正常输入框 -->
						<input 
							v-else
							type="text" 
							:placeholder="t('realName.qsrzjhm')" 
							v-model="idNumber" 
							:disabled="authStatus === 1"
						/>
					</view>
				</view>
			</view>

			<!-- 证件照片 - 已认证状态下完全隐藏 -->
			<view v-if="authStatus !== 2" class="form-item">
				<view class="form-label">{{ t('realName.zjzp') }}</view>
				<view class="id-photos">
					<view class="photo-upload" @click="(authStatus === 0 || authStatus === 3) ? chooseImage('front') : null">
						<image v-if="frontImage" :src="frontImage" mode="aspectFill" class="uploaded-image" :class="{ 'disabled': authStatus === 1 }"></image>
						<view v-else-if="authStatus === 0 || authStatus === 3" class="upload-placeholder">
							<text class="plus">+</text>
						</view>
					</view>
					<view class="photo-upload" @click="(authStatus === 0 || authStatus === 3) ? chooseImage('back') : null">
						<image v-if="backImage" :src="backImage" mode="aspectFill" class="uploaded-image" :class="{ 'disabled': authStatus === 1 }"></image>
						<view v-else-if="authStatus === 0 || authStatus === 3" class="upload-placeholder">
							<text class="plus">+</text>
						</view>
					</view>
				</view>
				<!-- 审核中状态隐藏照片提示 -->
				<view v-if="authStatus === 1" class="photo-hidden-tip">
					<text>照片已隐藏</text>
				</view>
			</view>
			
			<!-- 确认按钮 - 只在未认证或认证失败时显示 -->
			<view v-if="authStatus === 0 || authStatus === 3" class="confirm-btn" @click="submitVerification">
				{{ t('common.confirm') }}
			</view>
			
			<!-- 审核中漂浮蒙版 -->
			<view v-if="authStatus === 1 && showReviewOverlay" class="review-overlay" @click="closeReviewOverlay">
				<view class="review-modal" @click.stop>
					<view class="review-close" @click="closeReviewOverlay">
						<text class="close-icon">×</text>
					</view>
					<image src="/static/icon/review.svg" class="review-icon"></image>
					<text class="review-text">正在审核中</text>
					<text class="review-desc">我们正在审核您的认证信息，请耐心等待</text>
				</view>
			</view>
		</view>

		<!-- 证件类型选择器弹窗 -->
		<view class="id-type-selector" v-if="showIdTypeSelector">
			<view class="selector-mask" @click="showIdTypeSelector = false"></view>
			<view class="selector-content">
				<view class="selector-item">
					<view class="selector-item-content">
						<view class="left">
							<image src="/static/icon/zhenjian.svg" class="selector-icon"></image>
							<!-- <text>{{ t('realName.sfz') }}</text> -->
							<view class="left-text">{{ cardTypeList[selectedIdType] }}</view>
						</view>
						<view class="right">
							<image src="/static/icon/xiala1.svg" class="xiala"></image>
						</view>
					</view>
				</view>
				<view class="selector-item" v-for="(item,index) in cardTypeList" :key="index" @click="selectIdType(index)">
					<view class="selector-item-content">
						<view class="left">
							<view class="left-text">{{ item }}</view>
						</view>
						<view class="right">
							<image v-if="selectedIdType==index" src="/static/icon/selected.svg" class="check-icon"></image>
						</view>
					</view>
				</view>
			</view>
		</view>
		<GlobalPopup ref="popup"></GlobalPopup>
	</view>
</template>

<script setup>
	import {
		useI18n
	} from 'vue-i18n';
	import {
		ref,
		onMounted
	} from 'vue';
	import request from '@/utils/request';
	import { authApi } from '@/api/auth';
	
	const {
		t,
		locale
	} = useI18n();
	const popup = ref()
	// 表单数据
	const selectedIdType = ref(0); // 默认选择身份证
	const realName = ref('');
	const idNumber = ref('');
	const frontImage = ref('');
	const backImage = ref('');
	const frontImageUrl = ref(''); // 前面照片上传后的URL
	const backImageUrl = ref(''); // 背面照片上传后的URL
	const showIdTypeSelector = ref(false);
	const cardTypeList = ref([ t('realName.sfz'), t('realName.hz'), t('realName.jsz')])
	
	// 用户认证状态相关
	const userAuthInfo = ref(null); // 用户认证信息
	const authStatus = ref(0); // 认证状态：0-未认证，1-审核中，2-已认证，3-认证失败
	const isLoading = ref(true); // 页面加载状态
	const showReviewOverlay = ref(true); // 控制审核中蒙版的显示
	
	// 选择证件类型
	function selectIdType(type) {
		// selectedIdType.value = t('realName.sfz');
		selectedIdType.value = type;
		showIdTypeSelector.value = false;
	}

	// 关闭审核蒙版
	function closeReviewOverlay() {
		showReviewOverlay.value = false;
	}

	// 身份证号码脱敏处理函数
	function maskIdNumber(idNumber) {
		if (!idNumber || idNumber.length < 7) {
			return idNumber;
		}
		// 保留前三位和后四位，中间用*号替代
		const front = idNumber.substring(0, 3);
		const back = idNumber.substring(idNumber.length - 4);
		const maskLength = idNumber.length - 7;
		const mask = '*'.repeat(maskLength);
		return front + mask + back;
	}

	// 图片上传接口
	async function uploadImage(filePath) {
		try {
			uni.showLoading({
				title: t('common.uploading') || '上传中...'
			});
			
			const result = await new Promise((resolve, reject) => {
				uni.uploadFile({
					url: request.baseURL + '/app-api/infra/file/upload',
					filePath: filePath,
					name: 'file',
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('token')
					},
					success: (uploadRes) => {
						try {
							const data = JSON.parse(uploadRes.data);
							if (data.code === 0) {
								resolve(data.data);
							} else {
								reject(new Error(data.msg || '上传失败'));
							}
						} catch (e) {
							reject(new Error('上传响应解析失败'));
						}
					},
					fail: (error) => {
						reject(error);
					}
				});
			});
			
			uni.hideLoading();
			return result;
		} catch (error) {
			uni.hideLoading();
			uni.showToast({
				title: error.message || '上传失败',
				icon: 'none'
			});
			throw error;
		}
	}

	// 选择图片并自动上传
	async function chooseImage(type) {
		try {
			const res = await new Promise((resolve, reject) => {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: resolve,
					fail: reject
				});
			});
			
			const filePath = res.tempFilePaths[0];
			
			// 先显示本地图片
			if (type === 'front') {
				frontImage.value = filePath;
			} else {
				backImage.value = filePath;
			}
			
			// 自动上传图片
			const uploadResult = await uploadImage(filePath);
			
			// 保存上传后的URL
			if (type === 'front') {
				frontImageUrl.value = uploadResult;
				uni.showToast({
					title: '正面照片上传成功',
					icon: 'success'
				});
			} else {
				backImageUrl.value = uploadResult;
				uni.showToast({
					title: '背面照片上传成功',
					icon: 'success'
				});
			}
		} catch (error) {
			console.error('选择或上传图片失败:', error);
		}
	}
	// 实名认证提交接口
	async function submitRealNameAuth(data) {
		try {
			const response = await request.post('/app-api/member/user-auth/create', data);
			return response;
		} catch (error) {
			throw error;
		}
	}

	// 提交验证
	async function submitVerification() {
		if (!realName.value) {
			uni.showToast({
				title: t('realName.qsrzsxm'),
				icon: 'none'
			});
			return;
		}

		if (!idNumber.value) {
			uni.showToast({
				title: t('realName.qsrzjhm'),
				icon: 'none'
			});
			return;
		}

		if (!frontImage.value || !backImage.value) {
			uni.showToast({
				title: t('realName.qscjzp'),
				icon: 'none'
			});
			return;
		}

		// 检查图片是否已上传
		if (!frontImageUrl.value || !backImageUrl.value) {
			uni.showToast({
				title: '请等待图片上传完成',
				icon: 'none'
			});
			return;
		}

		try {
			uni.showLoading({
				title: '提交中...'
			});

			// 准备实名认证数据
			const authData = {
				number: idNumber.value,
				name: realName.value,
				frontImg: frontImageUrl.value,
				backImg: backImageUrl.value,
				authStatus: selectedIdType.value + 1 // 1是身份证，2是护照，3是驾驶证
			};

			// 调用实名认证接口
			const result = await submitRealNameAuth(authData);
			
			uni.hideLoading();

			if (result.code === 0) {
				// 提交成功
				popup.value.open({
					title: t('realName.tjcg'),
					content: t('realName.ddsh'),
					loading: true,
				});
				uni.setStorageSync('isReal', '1');
			} else {
				// 提交失败
				uni.showToast({
					title: result.msg || '提交失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.hideLoading();
			console.error('实名认证提交失败:', error);
			uni.showToast({
				title: error.message || '网络错误，请重试',
				icon: 'none'
			});
		}
	}

	// 获取用户认证状态
	async function getUserAuthStatus() {
		try {
			isLoading.value = true;
			const result = await authApi.getUserAuthStatus();
			
			if (result.code === 0 && result.data) {
				userAuthInfo.value = result.data;
				authStatus.value = result.data.authStatus;
				
				// 如果是审核中状态，显示蒙版
				if (result.data.authStatus === 1) {
					showReviewOverlay.value = true;
				}
				
				// 如果已有认证信息，填充表单
				if (result.data.authStatus !== 0) {
					realName.value = result.data.name || '';
					idNumber.value = result.data.number || '';
					frontImageUrl.value = result.data.frontImg || '';
					backImageUrl.value = result.data.backImg || '';
					// 同时赋值给显示用的变量
					frontImage.value = result.data.frontImg || '';
					backImage.value = result.data.backImg || '';
					selectedIdType.value = (result.data.authStatus - 1) || 0;
				}
			}
		} catch (error) {
			console.error('获取用户认证状态失败:', error);
			// 如果获取失败，默认为未认证状态
			authStatus.value = 0;
		} finally {
			isLoading.value = false;
		}
	}

	// 页面加载时获取用户认证状态
	onMounted(() => {
		getUserAuthStatus();
	});
</script>

<style scoped lang="scss">
	.content-box {
		min-height: 100vh;
		background-color: #F5F6FA;
		padding-top: 27.91rpx;
		padding-bottom: 100rpx;
		box-sizing: border-box;
	}

	.form-container {
		border-radius: 31.4rpx;
		background: rgba(255, 255, 255, 1);
		box-shadow: 1.74rpx 1.74rpx 5.23rpx rgba(102, 102, 102, 0.25);
		padding: 52.33rpx 55.82rpx 73.27rpx;
		margin: 0 34.89rpx;

		.form-item {
			margin-bottom: 34.89rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.form-label {
				font-size: 27.91rpx;
				font-weight: 400;
				letter-spacing: 0rpx;
				line-height: 40.42rpx;
				color: rgba(51, 51, 51, 1);
				margin-bottom: 17.45rpx;
				margin-left: 10.67rpx;
			}

			.form-input-container {
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-radius: 27.91rpx;
				background: rgba(249, 250, 251, 1);
				padding: 31.4rpx 52.33rpx;

				.form-input {
					display: flex;
					align-items: center;
					flex: 1;
					height: 100%;

					.input-icon {
						width: 34.89rpx;
						height: 34.89rpx;
						margin-right: 34.89rpx;
					}

					input {
						font-size: 27.91rpx;
						font-weight: 400;
						letter-spacing: 0rpx;
						line-height: 40.42rpx;
						color: rgba(51, 51, 51, 1);
					}

					text {
						font-size: 28rpx;
						color: rgba(51, 51, 51, 1);
					}

					.masked-id-number {
						font-size: 27.91rpx;
						font-weight: 400;
						letter-spacing: 0rpx;
						line-height: 40.42rpx;
						color: rgba(51, 51, 51, 1);
						flex: 1;
					}
				}
			}
		}
	}

	.arrow-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.id-photos {
		display: flex;
		justify-content: space-between;
	}

	.photo-upload {
		width: 275.6rpx;
		height: 195.36rpx;
		border-radius: 26.16rpx;
		border: 1.74rpx dashed rgba(196, 196, 196, 1);
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
	}

	.upload-placeholder {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
	}

	.plus {
		font-size: 27.91rpx;
		color: rgba(196, 196, 196, 1);
		;
	}

	.uploaded-image {
		width: 100%;
		height: 100%;
	}

	.confirm-btn {
		width: 570.38rpx;
		height: 97.68rpx;
		line-height: 97.68rpx;
		border-radius: 26.16rpx;
		background: linear-gradient(90deg, rgba(12, 193, 155, 1) 0%, rgba(91, 220, 222, 1) 34.03%, rgba(5, 145, 198, 1) 65.97%, rgba(2, 120, 220, 1) 100%);
		text-align: center;
		color: #FFFFFF;
		font-size: 31.4rpx;
		font-weight: 700;
		margin-top: 338.4rpx;
	}

	.id-type-selector {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 99999;

	}

	.selector-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(51, 51, 51, 0.3);
		backdrop-filter: blur(2rpx);
	}

	.selector-content {
		position: absolute;
		top: 280rpx;
		left: 90.70rpx;
		right: 90.70rpx;
		border-radius: 27.91rpx;
		background: rgba(249, 250, 251, 1);
		padding: 0 52.33rpx;
	}

	.selector-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 31.4rpx 0;
		border-bottom: 0.87rpx solid rgba(222, 220, 220, 1);
	}

	.selector-item-content {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		// padding-bottom: 27.91rpx;

		.left {
			display: flex;
			align-items: center;

			.selector-icon {
				width: 34.89rpx;
				height: 34.89rpx;

			}

			.left-text {
				margin-left: 34.89rpx;
				font-size: 27.91rpx;
				font-weight: 400;
				letter-spacing: 0rpx;
				line-height: 40.42rpx;
				color: rgba(51, 51, 51, 1);

				&.active {
					padding-left: 34.89rpx;
				}
			}
		}

		.right {
			width: 34.89rpx;
			height: 34.89rpx;
			.xiala{
				
				width: 21.72rpx;
				height: 12.99rpx;
			}
			image {
				width: 100%;
				height: 100%;
			}
		}


	}



	.check-icon {
		width: 27.91rpx;
		height: 27.91rpx;
	}

	/* 加载状态样式 */
	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 400rpx;
		font-size: 28rpx;
		color: #666;
	}

	/* 认证信息样式 */
	.auth-info {
		.auth-status-badge {
			display: inline-block;
			padding: 10rpx 20rpx;
			border-radius: 20rpx;
			font-size: 24rpx;
			font-weight: 500;
			margin-bottom: 30rpx;

			&.success {
				background: #e8f5e8;
				color: #52c41a;
			}

			&.pending {
				background: #fff7e6;
				color: #fa8c16;
			}

			&.failed {
				background: #fff2f0;
				color: #ff4d4f;
			}
		}

		.info-item {
			display: flex;
			margin-bottom: 20rpx;
			font-size: 28rpx;

			.label {
				color: #666;
				width: 160rpx;
			}

			.value {
				color: #333;
				flex: 1;
			}
		}

		.auth-photos {
			margin-top: 30rpx;

			.photo-item {
				margin-bottom: 20rpx;

				.photo-label {
					display: block;
					font-size: 24rpx;
					color: #666;
					margin-bottom: 10rpx;
				}

				.auth-image {
					width: 200rpx;
					height: 120rpx;
					border-radius: 10rpx;
					border: 1px solid #e8e8e8;
				}
			}
		}
	}

	/* 审核中容器样式 */
	.review-container {
		position: relative;
	}

	/* 审核中漂浮蒙版样式 */
	.review-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;

		.review-modal {
			background: white;
			border-radius: 20rpx;
			padding: 60rpx 40rpx;
			text-align: center;
			width: 500rpx;
			box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
			position: relative;

			.review-close {
				position: absolute;
				top: 20rpx;
				right: 20rpx;
				width: 60rpx;
				height: 60rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				cursor: pointer;
				
				.close-icon {
					font-size: 40rpx;
					color: #999;
					font-weight: bold;
					line-height: 1;
				}
				
				&:hover .close-icon {
					color: #666;
				}
			}

			.review-icon {
				width: 80rpx;
				height: 80rpx;
				margin-bottom: 20rpx;
			}

			.review-text {
				display: block;
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
				margin-bottom: 15rpx;
			}

			.review-desc {
				display: block;
				font-size: 26rpx;
				color: #666;
				line-height: 1.5;
			}
		}
	}

	// 状态提示样式
	.status-tip {
		margin-bottom: 30rpx;
		text-align: center;
	}

	// 禁用状态样式
	.form-input.disabled {
		background-color: #f5f5f5;
		opacity: 0.7;
		
		input {
			background-color: transparent;
			color: #999;
		}
	}

	.uploaded-image.disabled {
		opacity: 0.7;
		filter: grayscale(0.3);
	}

	// 照片隐藏提示
	.photo-hidden-tip {
		margin-top: 20rpx;
		text-align: center;
		
		text {
			font-size: 24rpx;
			color: #999;
			background-color: #f0f0f0;
			padding: 10rpx 20rpx;
			border-radius: 20rpx;
		}
	}
</style>